<?php

App::import('Model', 'User');
App::import('Model', 'Account');

class AccountsController extends AppController {

    public $helpers = array('Html', 'Form');
    public $helpers1 = array('Js' => array('DragDropHelpers'));
    public $helpers2 = array('Js' => array('EventHelpers'));
    public $helpers3 = array('Js' => array('permissionForm'));
    public $helpers4 = array('css' => array('permission'));

    public function index() {
        
    }

    /**
     * 
     * Description of "assign_pos"
     *
     * This function passes the arrays(unassignedUsers,moderators,editors,jEditors) from the controller 
     * to the view and then passes the new arrays from the view to the controller when the admin is done...
     *
     * @author karim kamel
     */
    public function assign_pos() {
        $user = new User();
        $account = new Account();
        $accID = $this->Auth->user('current_account');
        if ($accID == null) {
            $this->Session->setFlash('Please select an account');
        } else {
            $namearray = $account->getAccountNameByAccID($accID);
            $name = $namearray[0]['Account']['screen_name'];
            $this->set('name', $name);

            $mod = $user->getModeratorsByName($accID);
            $this->set('mod', $mod);
            $modlen = count($mod);
            $this->set('modlen', $modlen);

            $edi = $user->getEditorsByName($accID);
            $this->set('edi', $edi);
            $edilen = count($edi);
            $this->set('edilen', $edilen);

            if (!empty($this->request->data)) {
                //$this->redirect(array("index"));
                debug($this->request->data);
                $mod = $this->request->data['moderators1'];
                $ed = $this->request->data['editors1'];
                ClassRegistry::init('Account')->assignPos($mod, $ed, $accID);
            }
        }
    }

    public function selectAccount() {
        $this->autoRender = false;
        if (!empty($this->request->data)) {
            $ACCID = $this->Account->find('all', array('conditions' => array('screen_name' => $this->request->data['twitterAccountName']), 'fields' => array('id')));
            ClassRegistry::init('User')->updateAll(
                    array('current_account' => $ACCID[0]['Account']['id']), array('email' => $this->Auth->User('email')));
            $this->Session->write("Auth.User.current_account", $ACCID[0]['Account']['id']);
        }
    }

    /*
     * This method is responsible for the view to add clients.It asks twitter for an auth token and auth secret and adds them to session .And if the request was successful it will redirect to the same page.     
     * @return void
     * @author "Omar Ruedy"
     */

    public function addTwitterAccount() {
        if (!isset($_REQUEST['oauth_verifier'])) {
            $twitteroauth = new TwitterOAuth('JpsL9pQYCrNIXTFqWizM3Q', 'NetGak3BkvZq4JTucIbzH7549NeClMfl7ZBEclt2cSs');
            $request_token = $twitteroauth->getRequestToken('http://localhost/tweetar/Accounts/addTwitterAccount');

            $_SESSION['oauth_token'] = $request_token['oauth_token'];
            $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

            if ($twitteroauth->http_code == 200) {
                $redirect_url = $twitteroauth->getAuthorizeURL($request_token, false);

                $this->redirect($redirect_url);
            } else {
                $this->Session->setFlash('OH boy,I think something is wrong with your internet connection!');
            }
        } else {

            $connection = new TwitterOAuth('JpsL9pQYCrNIXTFqWizM3Q', 'NetGak3BkvZq4JTucIbzH7549NeClMfl7ZBEclt2cSs', $_SESSION['oauth_token'],
                            $_SESSION['oauth_token_secret']);

            $token_credentials = $connection->getAccessToken($_REQUEST['oauth_verifier']);

            $content = $connection->get('account/verify_credentials');
            $image = $content->profile_image_url;
            if (!empty($token_credentials['oauth_token']) && !empty($token_credentials['oauth_token_secret'])) {
                if (!($this->Account->isUnique('id', $token_credentials['user_id']))) {

                    $this->Session->setFlash('This account already exists ;)');
                } else {
                    $this->Account->set(array('id' => $token_credentials['user_id'], 'screen_name' => $token_credentials['screen_name'], 'access_token' => $token_credentials['oauth_token'], 'access_secret' => $token_credentials['oauth_token_secret'], 'image' => $image));
                    $this->Account->save();
                    ClassRegistry::init('AccountsUsers')->set(array('account_id' => $token_credentials['user_id'], 'user_email' => $this->Auth->User('email'), 'permission' => 'manager'));
                    ClassRegistry::init('AccountsUsers')->save();
                    $currentAccount = ClassRegistry::init('User')->find('first', array('conditions' => array('email' => $this->Auth->User('email')), 'fields' => 'current_account'));
                    if ($currentAccount['User']['current_account'] == null) {

                        ClassRegistry::init('User')->updateAll(
                                array('current_account' => $token_credentials['user_id']), array('email' => $this->Auth->User('email')));
                        $this->Session->write("Auth.User.current_account", $token_credentials['user_id']);
                    }
                    //$this->initStream($token_credentials['user_id']); # Initialize twitter stream.
                    $this->Session->setFlash('Account Successfully Added!');
                }
            } else {
                $this->Session->setFlash('Could not add account,please try again!');
            }
            $this->redirect(array('controller' => 'Accounts', 'action' => 'index'));
        }
    }

    /**
     * Executes the script which starts a twitter api stream.
     * @param int $accID The account for which the stream is to be opened.
     * @return void
     * @author KareemYousrii
     */
    function initStream($accID) {
        exec("nohup /Applications/MAMP/bin/php/php5.4.4/bin/php /Applications/MAMP/htdocs/tweetar/app/Vendor/Analytics.php $accID TRUE > /dev/null 2>&1 &");
    }

    function db() {
        $this->Account->ddb();
    }

}

?>
